package com.work.yshop.mvp.presenter;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.AgriTechContract;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 农技学堂页面的Presenter实现
 */
public class AgriTechPresenter implements AgriTechContract.Presenter {

    private static final String TAG = "AgriTechPresenter";
    private WeakReference<AgriTechContract.View> viewRef;
    private Context context;
    private List<Article> articleList;
    
    // 缓存不同分类的文章列表
    private Map<String, List<Article>> categoryArticlesCache;
    // 全部文章缓存
    private List<Article> allArticlesCache;
    // 当前选中的分类
    private String currentCategory = null;

    public AgriTechPresenter(Context context) {
        this.context = context;
        this.articleList = new ArrayList<>();
        this.categoryArticlesCache = new HashMap<>();
        this.allArticlesCache = new ArrayList<>();
    }

    @Override
    public void attachView(AgriTechContract.View view) {
        viewRef = new WeakReference<>(view);
    }

    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }

    @Override
    public void loadArticles() {
        if (getView() == null) return;

        Log.d(TAG, "开始加载所有文章");
        getView().showLoading();
        
        currentCategory = null;
        
        // 检查是否有缓存
        if (!allArticlesCache.isEmpty()) {
            Log.d(TAG, "使用缓存的所有文章数据: " + allArticlesCache.size() + "篇");
            setArticles(allArticlesCache);
            return;
        }

        // 使用AsyncTask在后台线程中查询ContentProvider
        new LoadArticlesTask(context, this, null).execute();
    }

    @Override
    public void loadArticlesByCategory(String category) {
        if (getView() == null) return;

        Log.d(TAG, "开始加载分类文章: " + category);
        getView().showLoading();
        
        currentCategory = category;
        
        // 检查是否有缓存
        if (categoryArticlesCache.containsKey(category) && !categoryArticlesCache.get(category).isEmpty()) {
            Log.d(TAG, "使用缓存的分类文章数据: " + category + ", " + categoryArticlesCache.get(category).size() + "篇");
            setArticles(categoryArticlesCache.get(category));
            return;
        }

        // 使用AsyncTask在后台线程中查询ContentProvider，传入分类参数
        new LoadArticlesTask(context, this, category).execute();
    }

    @Override
    public void refreshArticles() {
        // 清除缓存
        if (currentCategory == null) {
            allArticlesCache.clear();
            loadArticles();
        } else {
            categoryArticlesCache.remove(currentCategory);
            loadArticlesByCategory(currentCategory);
        }
    }

    @Override
    public void onArticleClick(Article article) {
        if (getView() == null) return;
        getView().navigateToArticleDetail(article);
    }

    @Override
    public void onAddArticleClick() {
        if (getView() == null) return;
        getView().navigateToAddArticle();
    }

    /**
     * 获取当前绑定的View
     */
    private AgriTechContract.View getView() {
        return viewRef != null ? viewRef.get() : null;
    }

    /**
     * 设置文章列表
     */
    void setArticles(List<Article> articles) {
        // 首先处理null的情况，确保articles是一个列表
        if (articles == null) {
            articles = new ArrayList<>();
        }
        
        this.articleList = articles;

        if (getView() == null) return;

        getView().hideLoading();
        
        // 无论列表是否为空，都更新缓存，以避免重复加载
        if (currentCategory == null) {
            allArticlesCache = new ArrayList<>(articles);
            Log.d(TAG, "更新'推荐'分类缓存，数量: " + allArticlesCache.size());
        } else {
            categoryArticlesCache.put(currentCategory, new ArrayList<>(articles));
            Log.d(TAG, "更新'" + currentCategory + "'分类缓存，数量: " + articles.size());
        }

        if (articles.isEmpty()) {
            Log.d(TAG, "文章列表为空，显示空视图");
            getView().showEmptyView();
        } else {
            Log.d(TAG, "显示文章列表: " + articles.size() + "篇");
            getView().showArticles(articles);
        }
    }

    /**
     * 显示错误信息
     */
    void showError(String message) {
        if (getView() == null) return;

        Log.e(TAG, "加载文章出错: " + message);
        getView().hideLoading();
        getView().showError(message);
    }

    /**
     * 异步任务，用于在后台线程中查询ContentProvider
     */
    private static class LoadArticlesTask extends AsyncTask<Void, Void, List<Article>> {

        private Context context;
        private WeakReference<AgriTechPresenter> presenterRef;
        private Exception exception;
        private String category; // 添加分类参数

        LoadArticlesTask(Context context, AgriTechPresenter presenter, String category) {
            this.context = context;
            this.presenterRef = new WeakReference<>(presenter);
            this.category = category;
        }

        @Override
        protected List<Article> doInBackground(Void... voids) {
            List<Article> articles = new ArrayList<>();

            try {
                Log.d(TAG, "后台线程开始查询文章");
                // 查询ContentProvider
                Uri uri = ArticleProvider.CONTENT_URI;
                
                // 获取当前用户类型
                int userType = UserSession.getInstance().getUserType();
                
                // 根据分类筛选
                String selection = null;
                String[] selectionArgs = null;
                
                if (category != null && !category.isEmpty() && !category.equals("推荐")) {
                    selection = "category = ?";
                    selectionArgs = new String[]{category};
                    Log.d(TAG, "按分类筛选: " + category);
                } else {
                    // 查询所有文章
                    selection = null;
                    selectionArgs = null;
                    Log.d(TAG, "显示所有文章(推荐)");
                }
                
                Cursor cursor = context.getContentResolver().query(
                        uri,
                        null,
                        selection,
                        selectionArgs,
                        "publish_date DESC" // 按发布日期降序排序
                );

                if (cursor != null) {
                    Log.d(TAG, "查询到的文章数: " + cursor.getCount());
                    try {
                        int idIndex = cursor.getColumnIndex("_id");
                        int titleIndex = cursor.getColumnIndex("title");
                        int summaryIndex = cursor.getColumnIndex("summary");
                        int contentIndex = cursor.getColumnIndex("content");
                        int imageUrlIndex = cursor.getColumnIndex("image_url");
                        int publishDateIndex = cursor.getColumnIndex("publish_date");
                        int viewCountIndex = cursor.getColumnIndex("view_count");
                        int categoryIndex = cursor.getColumnIndex("category");
                        
                        while (cursor.moveToNext()) {
                            // 从Cursor中提取文章数据，使用安全的方式获取列索引
                            int id = idIndex != -1 ? cursor.getInt(idIndex) : 0;
                            String title = titleIndex != -1 ? cursor.getString(titleIndex) : "";
                            String summary = summaryIndex != -1 ? cursor.getString(summaryIndex) : "";
                            String content = contentIndex != -1 ? cursor.getString(contentIndex) : "";
                            String imageUrl = imageUrlIndex != -1 ? cursor.getString(imageUrlIndex) : "";
                            String publishDate = publishDateIndex != -1 ? cursor.getString(publishDateIndex) : "";
                            int viewCount = viewCountIndex != -1 ? cursor.getInt(viewCountIndex) : 0;
                            String articleCategory = categoryIndex != -1 ? cursor.getString(categoryIndex) : "";

                            // 创建文章对象并添加到列表
                            Article article = new Article(id, title, summary, content, imageUrl, publishDate, viewCount, articleCategory);
                            articles.add(article);
                            
                            Log.d(TAG, "添加文章: " + title + ", 分类: " + articleCategory);
                        }
                    } finally {
                        cursor.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                exception = e;
                Log.e(TAG, "查询文章时出错", e);
                return null;
            }

            Log.d(TAG, "后台线程查询完成，文章数: " + articles.size());
            return articles;
        }

        @Override
        protected void onPostExecute(List<Article> articles) {
            AgriTechPresenter presenter = presenterRef.get();
            if (presenter == null) return;

            if (exception != null) {
                Log.e(TAG, "加载文章异常", exception);
                presenter.showError("加载文章出错: " + exception.getMessage());
            } else {
                Log.d(TAG, "后台加载完成，文章数量: " + (articles != null ? articles.size() : 0));
                presenter.setArticles(articles);
            }
        }
    }
}
